package com.restaurantonlineorder.oauth.handler;

import com.restaurantonlineorder.oauth.utils.ResponseUtil;
import com.restaurantonlineorder.oauth.vo.resp.AuthResp;
import com.restaurantonlineorder.response.BaseResult;
import com.restaurantonlineorder.utils.JwtUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Optional;

/**
 * @author 熊宇
 * @date 2022/7/20 22:35
 * @description 成功和处理逻辑
 */

@Component
public class DefaultAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    /**
     * 成功后，生成token
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        UserDetails principal = (UserDetails) authentication.getPrincipal();

        //获取手机号
        String phone = authentication.getName();
        Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();
        Optional<String> first = authorities.stream().map(grantedAuthority -> grantedAuthority.getAuthority()).findFirst();

        //生成token
        String token = JwtUtil.generateToken(phone, first.get());
        AuthResp authResp = new AuthResp();
        authResp.setToken(token);
        authResp.setUserInfo(principal);

        ResponseUtil.sendMessage(response, BaseResult.success(authResp));
    }
}
